<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="科目" prop="subjectId">
        <el-select v-model="queryParams.subjectId" placeholder="请选择科目">
            <el-option
                v-for="subject in subjectOptions"
                :key="subject.subjectId"
                :label="subject.subjectName"
                :value="subject.subjectId"
              />
          </el-select>
      </el-form-item>
      <!--
      <el-form-item label="章节编号" prop="itemCode">
        <el-input
          v-model="queryParams.itemCode"
          placeholder="请输入章节编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      -->
      <el-form-item label="章节名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入章节名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态">
            <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
          </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['edu:subjectItems:add']"
        >新增章</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="subjectItemsList" row-key="itemId"
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <!--<el-table-column label="章节ID" align="center" prop="itemId" />-->
      <el-table-column label="章名称" align="left" prop="itemName" >
        <template slot-scope="scope">
          <span v-if="scope.row.itemType === '0'">{{scope.row.itemName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="节名称" align="left" prop="itemName" >
        <template slot-scope="scope">
          <span v-if="scope.row.itemType === '1'">{{scope.row.itemName}}</span>
        </template>
      </el-table-column>
      <el-table-column label="章节编号" align="center" prop="itemCode" />
      <el-table-column label="科目" align="center" prop="subjectName" />
      <!--<el-table-column label="章节内容" align="center" prop="content" />-->
      <el-table-column label="状态" :formatter="statusFormat" align="center" prop="status" />
      <el-table-column label="显示顺序" align="center" prop="itemSort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"> 
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['edu:subjectItems:edit']"
          >修改</el-button>
          <el-button 
            size="mini" 
            type="text" 
            icon="el-icon-plus" 
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:dept:add']"
            v-if="scope.row.itemType === '0'"
          >新增节</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['edu:subjectItems:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  -->
    <!-- 添加或修改科目章节信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item v-if="form.parentId === 0 || form.parentId === undefined" label="科目" prop="subjectId">
          <el-select v-model="form.subjectId" placeholder="请选择科目">
            <el-option
                v-for="subject in subjectOptions"
                :key="subject.subjectId"
                :label="subject.subjectName"
                :value="subject.subjectId"
              />
          </el-select>
        </el-form-item>
        <!--
        <el-form-item v-if="form.parentId === 0 || form.parentId  === undefined " label="父章节" prop="parentId">
          <treeselect v-model="form.parentId" :options="subjectItemOptions" :normalizer="normalizer" placeholder="选择父章节" />
        </el-form-item>
        -->
        <el-form-item label="章节编号" prop="itemCode">
          <el-input v-model="form.itemCode" placeholder="请输入章节编号" />
        </el-form-item>
        <el-form-item label="章节名称" prop="itemName">
          <el-input v-model="form.itemName" placeholder="请输入章节名称" />
        </el-form-item>
        <el-form-item label="章节内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
                    <el-radio
                      v-for="dict in statusOptions"
                      :key="dict.dictValue"
                      :label="dict.dictValue"
                    >{{dict.dictLabel}}</el-radio>
                  </el-radio-group>
        </el-form-item>
        <el-form-item label="显示顺序" prop="itemSort">
          <el-input v-model="form.itemSort" placeholder="请输入显示顺序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button size="mini" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSubjectItems, getSubjectItems, delSubjectItems, addSubjectItems, updateSubjectItems, exportSubjectItems,listItemExcludeChild } from "@/api/edu/subjectItems";
import { getSubjectsAll } from "@/api/edu/subjects";
import Editor from '@/components/Editor';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "SubjectItems",
  components: { Editor, Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 科目章节信息表格数据
      subjectItemsList: [],
      subjectOptions: [],
      statusOptions: [],
      subjectItemOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        //pageNum: 1,
        //pageSize: 10,
        subjectId: null,
        parentId: null,
        itemCode: null,
        itemName: null,
        content: null,
        status: null,
        itemSort: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        subjectId: [
          { required: true, message: "科目ID不能为空", trigger: "blur" }
        ],
        parentId: [
          { required: true, message: "父章节ID不能为空", trigger: "blur" }
        ],
        itemSort: [
          { required: true, message: "显示顺序不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    
    this.getSubjects();
    this.getDicts("sys_normal_disable").then(response => {
      this.statusOptions = response.data;
    });
    this.getList();
  },
  methods: {
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    getSubjects() {
      getSubjectsAll().then(response => {
        this.subjectOptions = response.data
      })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.itemId,
        label: node.itemName,
        children: node.children
      };
    },
    /** 查询科目章节信息列表 */
    getList() {
      this.loading = true;
      listSubjectItems(this.queryParams).then(response => {
        this.subjectItemsList = this.handleTree(response.data, "itemId");
        //this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        itemId: null,
        subjectId: null,
        subjectName: null,
        parentId: null,
        itemCode: null,
        itemName: null,
        content: null,
        itemType: null,
        status: "0",
        itemSort: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.itemId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      console.log(JSON.stringify(row))
      if (row !== undefined && row.itemId && row.subjectId) {
        this.form.parentId = row.itemId;
        this.form.subjectId = row.subjectId;
      } else {
        this.form.parentId = 0;
        this.form.subjectId = null;
      }
      this.open = true;
      this.title = "添加科目章节信息";
      listSubjectItems().then(response => {
	        this.subjectItemOptions = this.handleTree(response.data, "itemId");
          //console.log(JSON.stringify(this.subjectItemOptions))
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getSubjectItems(row.itemId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改科目章节信息";
      });
      listItemExcludeChild(row.itemId).then(response => {
	        this.subjectItemOptions = this.handleTree(response.data, "itemId");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.parentId !== 0) {
            this.form.itemType = '1' // 节数据
          } else {
             this.form.itemType = '0' 
          }
          if (this.form.itemId != null) {
            updateSubjectItems(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSubjectItems(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const itemIds = row.itemId || this.ids;
      this.$confirm('是否确认删除科目章节信息编号为"' + itemIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delSubjectItems(itemIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有科目章节信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportSubjectItems(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
